//
//  MLAHttpManage.m
//  MagicLampApp
//
//  Created by Zheng on 2018/12/25.
//  Copyright © 2018 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAHttpManage.h"

static MLAHttpManage *instance = nil;
AFHTTPSessionManager *manager;

@implementation MLAHttpManage

+ (NSURLSessionDataTask *)postHttpType:(MLAHttpRequestType)rType hostType:(MLAHttpHostType)type api:(NSString *)api params:(nullable id)params success:(void(^)(id response,NSString *msg))success failure:(void(^)(void))failure {

    
    NSMutableDictionary *paramsDic;
    if (![api containsString:@"http"]) {
        NSString *host = [[self class] getHostWithType:type];
        api = [NSString stringWithFormat:@"%@%@",host,api];
        if ([params isKindOfClass:[NSDictionary class]] || params == nil) {
            paramsDic = [[NSMutableDictionary alloc] initWithDictionary:params];
            [paramsDic setObject:kApi_Key forKey:@"apiKey"];
        }
    }
    

    NSURLSessionDataTask *task;
    
    switch (rType) {
        case MLAHttpRequestType_Get: {
            [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];

            if (kGetToken) {
                [manager.requestSerializer setValue:kGetToken forHTTPHeaderField:@"X-SS-USER-TOKEN"];
            }

            task = [manager GET:api parameters:paramsDic progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                success(responseObject,@"");
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"error == %@",error);
                failure();
            }];
        }
            break;
        case MLAHttpRequestType_Post:
        case MLAHttpRequestType_Put:
        {

            manager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            NSString *type;
            if (rType == MLAHttpRequestType_Post) {
                type = @"POST";
            } else if (rType == MLAHttpRequestType_Put) {
                type = @"PUT";
            }
            
            NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:type URLString:api parameters:nil error:nil];
            [req setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
            [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [req setValue:kApi_Key forHTTPHeaderField:@"X-SS-API-KEY"];
            if (kGetToken) {
                [req setValue:kGetToken forHTTPHeaderField:@"X-SS-USER-TOKEN"];
            }

            [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                if (error) {
                    NSLog(@"error == %@",error);
                    failure();
                } else {
                    success(responseObject,@"");
                }
            }] resume];
            
        }
            break;
        
    }
    return task;

}




#pragma mark - 获取Host地址
+ (NSString *)getHostWithType:(MLAHttpHostType)type {
    NSString *host;
    switch (type) {
        case MLAHttpHostType_Api:
            host = kBase_URL;
            break;
        case MLAHttpHostType_Shop:
            host = kShoping_URL;
            break;
    }

    return host;
}


#pragma mark - 初始化
+ (void)load {
    [MLAHttpManage defaultManager];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        manager = [AFHTTPSessionManager manager];
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
    }
    return self;
}

+ (instancetype)defaultManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (instance) {
        return instance;
    } else {
        return [MLAHttpManage defaultManager];
    }
}

- (id)copy {
    return [MLAHttpManage defaultManager];
}

- (id)mutableCopy {
    return [MLAHttpManage defaultManager];
}




@end
